package com.example.musicapp.ui.player

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.SeekBar
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.bumptech.glide.Glide
import com.example.musicapp.R
import com.example.musicapp.databinding.FragmentPlayerBinding
import com.example.musicapp.viewmodel.MusicViewModel

class PlayerFragment : Fragment() {
    private var _binding: FragmentPlayerBinding? = null
    private val binding get() = _binding!!
    private val viewModel: MusicViewModel by activityViewModels()
    
    // 添加旋转动画
    private var rotateAnimation: ObjectAnimator? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPlayerBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupUI()
        observeViewModel()
        setupRotateAnimation()
    }

    private fun setupUI() {
        binding.apply {
            playPauseButton.setOnClickListener {
                viewModel.togglePlayPause()
            }

            previousButton.setOnClickListener {
                viewModel.playPrevious()
            }

            nextButton.setOnClickListener {
                viewModel.playNext()
            }

            seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                    if (fromUser) {
                        viewModel.seekTo(progress)
                    }
                    // 更新时间显示
                    currentTime.text = formatTime(progress)
                }

                override fun onStartTrackingTouch(seekBar: SeekBar?) {}
                override fun onStopTrackingTouch(seekBar: SeekBar?) {}
            })
        }
    }

    private fun setupRotateAnimation() {
        rotateAnimation = ObjectAnimator.ofFloat(binding.albumCover, View.ROTATION, 0f, 360f).apply {
            duration = 10000 // 10秒转一圈
            repeatCount = ObjectAnimator.INFINITE
            interpolator = LinearInterpolator()
            repeatMode = ObjectAnimator.RESTART
        }
        // 如果当前正在播放，立即开始动画
        if (viewModel.isPlaying.value == true) {
            rotateAnimation?.start()
        }
    }

    private fun observeViewModel() {
        viewModel.currentSong.observe(viewLifecycleOwner) { song ->
            song?.let {
                binding.apply {
                    songTitle.text = it.title
                    artistName.text = it.artist
                    Glide.with(this@PlayerFragment)
                        .load(it.coverUrl)
                        .centerCrop()
                        .into(albumCover)
                }
                // 新歌曲加载时，重新开始动画
                rotateAnimation?.cancel()
                rotateAnimation?.start()
            }
        }

        viewModel.isPlaying.observe(viewLifecycleOwner) { isPlaying ->
            binding.playPauseButton.setImageResource(
                if (isPlaying) android.R.drawable.ic_media_pause
                else android.R.drawable.ic_media_play
            )
            
            // 控制旋转动画
            if (isPlaying) {
                if (rotateAnimation?.isPaused == true) {
                    rotateAnimation?.resume()  // 如果是暂停状态，则从暂停处继续
                } else {
                    rotateAnimation?.start()   // 如果是初次播放或已停止，则重新开始
                }
            } else {
                rotateAnimation?.pause()  // 暂停动画，保持当前角度
            }
        }

        viewModel.currentProgress.observe(viewLifecycleOwner) { progress ->
            binding.apply {
                seekBar.progress = progress
                currentTime.text = formatTime(progress)
            }
        }

        viewModel.duration.observe(viewLifecycleOwner) { duration ->
            binding.apply {
                seekBar.max = duration
                totalTime.text = formatTime(duration)
            }
        }
    }

    private fun formatTime(seconds: Int): String {
        val minutes = seconds / 60
        val remainingSeconds = seconds % 60
        return String.format("%02d:%02d", minutes, remainingSeconds)
    }

    override fun onResume() {
        super.onResume()
        // 如果当前正在播放，从暂停处继续动画
        if (viewModel.isPlaying.value == true) {
            if (rotateAnimation?.isPaused == true) {
                rotateAnimation?.resume()
            } else {
                rotateAnimation?.start()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        // 暂停动画
        rotateAnimation?.pause()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清理动画
        rotateAnimation?.cancel()
        rotateAnimation = null
        _binding = null
    }
} 